<script setup lang="ts">
import { h, render } from 'vue'
import { RouteRecordRaw, useRoute, useRouter } from 'vue-router'
import { ConfigStore } from '@src/store/config.store'
const store = ConfigStore()
const routes = useRoute()
const router = useRouter()
const routesList = ref<RouteRecordRaw[]>([])
const curve = ref<string>('/home')
let r = router.getRoutes().filter((item) => {
  return item.meta.type === 'menu'
})
const props = defineProps({
  routes: {
    type: Array<RouteRecordRaw>,
    default: () => {
      return []
    },
  },
})
routesList.value = r
// r.reduce((acc, cur) => {
//   acc.push(...cur.children)
//   return acc
// }, [] as RouteRecordRaw[])
function handleToRouter(path: string) {
  if (path.startsWith('/')) {
    router.push({ path })
  } else {
    router.push({ path: '/' + path })
  }
}
watch(
  () => routes.fullPath,
  (newv) => {
    curve.value = newv
  },
  {
    immediate: true,
  },
)
function renderIcons(name: string) {
  let i = resolveComponent(name)
  return h(i)
}
</script>
<template>
  <ElMenu :default-active="curve" active-text-color="#ffd04b" background-color="#545c64" text-color="#fff" :collapse="store.expand">
    <template v-for="(item, index) in routesList" :key="index">
      <template v-if="item.children && item.children?.length > 0">
        <ElSubMenu class="menu-sub-item" :key="index" :index="item.path">
          <template #title>
            <component v-if="item?.meta?.icon" :is="renderIcons(item?.meta?.icon as string)"></component>
            <span>{{ item?.meta?.title }}</span>
          </template>
          <ElMenuItem class="menu-item-wrapper" v-for="(cItem, cIndex) in item.children" :key="cIndex" :index="cItem.path" @click="handleToRouter(cItem.path)">
            <component v-if="item?.meta?.icon" :is="renderIcons(cItem?.meta?.icon as string)"></component>
            <span>{{ cItem?.meta?.title }}</span>
          </ElMenuItem>
        </ElSubMenu>
      </template>
      <template v-else>
        <ElMenuItem class="menu-item-wrapper" @click="handleToRouter(item.path)" :key="index" :index="item.path">
          <component v-if="item?.meta?.icon" :is="renderIcons(item?.meta?.icon as string)"></component>
          <span>{{ item?.meta?.title }}</span>
        </ElMenuItem>
      </template>
    </template>
  </ElMenu>
</template>
<style lang="scss" scoped>
.menu-sub-item {
  ::v-deep(.el-sub-menu__title) {
    padding-right: 20px;
    svg {
      width: 1em;
      height: 1em;
      font-size: 14px;
    }
    span {
      margin-left: 10px;
      font-size: 16px;
    }
  }
}
.menu-item-wrapper {
  display: flex;
  align-items: center;

  > svg {
    width: 1em;
    height: 1em;
    font-size: 14px;
  }
  > span {
    margin-left: 10px;
    font-size: 16px;
  }
}
</style>
